package lookas;

import java.awt.geom.AffineTransform;
import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

import com.sun.image.codec.jpeg.ImageFormatException;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGEncodeParam;
import com.sun.image.codec.jpeg.JPEGImageDecoder;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

public class Jpeg{

    public static void saveImageToDisk(BufferedImage bi, String str){
        if(bi != null && str != null){

            // save image as Jpeg
            FileOutputStream out = null;
            try{
                out = new FileOutputStream(str);
            }catch(java.io.FileNotFoundException fnf){
                System.out.println("File Not Found");
            }

            JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
            JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(bi);
            param.setQuality(0.75f, false);

            try{
                encoder.encode(bi);
                out.close();
            }catch(java.io.IOException io){
                System.out.println(io);
            }
        }
    }

    public static BufferedImage scaleToSize(int nMaxWidth, int nMaxHeight,
        BufferedImage imgSrc){
        int nHeight = imgSrc.getHeight();
        int nWidth = imgSrc.getWidth();
        double scaleX = (double)nMaxWidth / (double)nWidth;
        double scaleY = (double)nMaxHeight / (double)nHeight;
        double fScale = Math.min(scaleX, scaleY);
        return scale(fScale, imgSrc);
    }

    public static BufferedImage scale(double scale, BufferedImage srcImg){
        if(scale == 1){
            return srcImg;
        }
        AffineTransformOp op = new AffineTransformOp(AffineTransform
            .getScaleInstance(scale, scale), null);
        return op.filter(srcImg, null);
    }

    public static BufferedImage loadBufferedImage(String fileName)
        throws ImageFormatException, IOException{

        FileInputStream fis = new FileInputStream(fileName);
        JPEGImageDecoder decoder = JPEGCodec.createJPEGDecoder(fis);
        BufferedImage bi = decoder.decodeAsBufferedImage();
        fis.close();
        return bi;
    }

    public static void main(String[] args) throws Exception{
        BufferedImage image = Jpeg
            .loadBufferedImage("c:\\download\\bridge-1600.jpg");
        BufferedImage scale = Jpeg.scaleToSize(200, 200, image);
        Jpeg.saveImageToDisk(scale, "c:/DSCF3317_small.JPG");
    }
}
